<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

class UserAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = trim(str_ireplace('Bearer', '', $request->header('Authorization', $request->get('token'))));

        if ($token) {
            try {
                if ($user = JWTAuth::authenticate($token)) {
                    return $next($request);
                }
            } catch (TokenExpiredException $e) {
                abort(401, 'token已过期');
            } catch (TokenInvalidException $e) {
                abort(401, 'token无效');
            } catch (JWTException $e) {
                \Log::error('>>>>> JWTException: ' . $e->getMessage());
            } catch (\Exception $e) {
                \Log::error('>>>>> 登录检验异常! Exception: ' . $e->getMessage());
            }
        }

        abort(401);
    }
}
